package server;


import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

import event.Event;
import event.EventHandler;

public class EventManager<T extends Event, S extends EventHandler> implements Runnable {

	private final ArrayList<S> mHandlers = new ArrayList<S>();
	private final BlockingQueue<T> mQueue = new PriorityBlockingQueue<T>();
	
	public EventManager() {

	}
	
	/**
	 * Place items in the queue.
	 * 
	 * @param item
	 */
	public void put(T item) {
		try {
			mQueue.put(item);
		} catch (InterruptedException e) {
			
		}
	}

	@Override
	public void run() {
		try {
			for (;;) {
				handle(mQueue.take());
			}
		} catch (InterruptedException e) {

		}
	}

	private void handle(T item) {
		for(S handler : mHandlers) {
			handler.handle(item);
		}
	}
	
	public void register(S handler) {
		mHandlers.add(handler);
	}
	
	public void unregister(S handler) {
		mHandlers.remove(handler);
	}

}
